﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Data.Objects;


namespace RL
{
    /// <summary>
    /// Логика взаимодействия для wVehicleTypeItem.xaml
    /// </summary>
    public partial class wVehicleTypeItem : Window
    {

        private vehicle_type cur_item;
        private RL.routelistEntities routelistEntities;

        public routelistEntities ContextDB { get { return routelistEntities;} set { routelistEntities = value; } }

        public vehicle_type VehicleType
        {
            get { return (vehicle_type)GetValue(VehicleTypeProperty); }
            set { SetValue(VehicleTypeProperty, value); }
        }

        // Using a DependencyProperty as the backing store for VehicleType.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty VehicleTypeProperty =
            DependencyProperty.Register("VehicleType", typeof(vehicle_type), typeof(wVehicleTypeItem), new UIPropertyMetadata(null, new PropertyChangedCallback(propChanged)));

        private static void propChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            wVehicleTypeItem item = d as wVehicleTypeItem;
            if (null == item) return;
            item.cur_item = (vehicle_type)e.NewValue;

        }



        public int? VehicleTypeID
        {
            get { return (int?)GetValue(VehicleTypeIDProperty); }
            set { SetValue(VehicleTypeIDProperty, value); }
        }

        // Using a DependencyProperty as the backing store for VehicleTypeID.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty VehicleTypeIDProperty =
            DependencyProperty.Register("VehicleTypeID", typeof(int?), typeof(wVehicleTypeItem), new UIPropertyMetadata(null, new PropertyChangedCallback(vehicleTypeID)));

        public static void vehicleTypeID(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            wVehicleTypeItem item = d as wVehicleTypeItem;
            if (null == d) return;
            if (null == item.routelistEntities) return;
            int? val = (int?)e.NewValue;
            vehicle_type it = (from o in item.routelistEntities.vehicle_type where o.id == val select o).FirstOrDefault();
            item.VehicleType = it;
        }

        public wVehicleTypeItem()
        {
            InitializeComponent();
            if (System.ComponentModel.DesignerProperties.GetIsInDesignMode(this)) return;
            routelistEntities = new RL.routelistEntities();
        }

        private void buttonSave_Click(object sender, RoutedEventArgs e)
        {
            if (true == SaveData())
            {
                try
                {
                    DialogResult = true; 
                }
                catch (Exception)
                {
                }
            }
        }

        private System.Data.Objects.ObjectQuery<vehicle_type> Getvehicle_typeQuery(routelistEntities routelistEntities)
        {
            // Автоматически созданный код

            System.Data.Objects.ObjectQuery<RL.vehicle_type> vehicle_typeQuery = routelistEntities.vehicle_type.Where("it.id=@prm", new ObjectParameter("prm",VehicleType.id));
            // Для явной загрузки данных, возможно, потребуется добавить методы Include, аналогичные показанным ниже:
            // vehicle_typeQuery = vehicle_typeQuery.Include("vehicle_type.fuel_type").
            // Дополнительные сведения см. по ссылке http://go.microsoft.com/fwlink/?LinkId=157380
            // Обновите запрос для включения данных FuelVehicleTypeNorm в vehicle_type. Можно изменить этот код как требуется.
            vehicle_typeQuery = vehicle_typeQuery.Include("FuelVehicleTypeNorm");
            // Возвращает ObjectQuery.
            return vehicle_typeQuery;
        }

        private System.Data.Objects.ObjectQuery<RL.fuel_type> GetFuelTypeQuery(routelistEntities routelistEntities)
        {
            System.Data.Objects.ObjectQuery<RL.fuel_type> fuel_typeQuery = routelistEntities.fuel_type;
            return fuel_typeQuery;
        }

        private System.Data.Objects.ObjectQuery<RL.FuelVehicleTypeNorm> GetvehicleTypeFuelNorm(vehicle_type vehicle_type)
        {
            // Автоматически созданный код
            if (null == vehicle_type) return null;
            //
            System.Data.Objects.ObjectQuery<RL.FuelVehicleTypeNorm> vehicle_typeQuery = routelistEntities.FuelVehicleTypeNorm.Where("it.id_type_vehicle=@prm", new ObjectParameter("prm", VehicleType.id)); ;
            // Для явной загрузки данных, возможно, потребуется добавить методы Include, аналогичные показанным ниже:
            // vehicle_typeQuery = vehicle_typeQuery.Include("vehicle_type.fuel_type").
            // Дополнительные сведения см. по ссылке http://go.microsoft.com/fwlink/?LinkId=157380
            // Обновите запрос для включения данных FuelVehicleTypeNorm в vehicle_type. Можно изменить этот код как требуется.
            // Возвращает ObjectQuery.
            return vehicle_typeQuery;
        }

        //private IEnumerable<RL.FuelVehicleTypeNorm> GetvehicleTypeFuel(vehicle_type vehicle_type)
        //{
        //    IEnumerable<RL.FuelVehicleTypeNorm> VehicleTypeFuelQuery = from o in vehicle_type.FuelVehicleTypeNorm select o;
        //    return VehicleTypeFuelQuery;
        //}

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {

            //RL.routelistEntities routelistEntities = new RL.routelistEntities();
            // Загрузить данные в vehicle_type. Можно изменить этот код как требуется.
            //System.Windows.Data.CollectionViewSource vehicle_typeViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("vehicle_typeViewSource")));
            //  System.Data.Objects.ObjectQuery<RL.vehicle_type> vehicle_typeQuery = this.Getvehicle_typeQuery(routelistEntities);
            //grid1.DataContext = VehicleType;// vehicle_typeQuery.Execute(System.Data.Objects.MergeOption.AppendOnly);
            System.Windows.Data.CollectionViewSource cvs = (CollectionViewSource)this.Resources["VehicletypeFuelSource"];
            if (null == ContextDB)
            {
                
            } else
            {
                CollectionViewSource cvs_ft = (CollectionViewSource)this.Resources["FuelTypeSource"];
                System.Data.Objects.ObjectQuery<fuel_type> ftq = GetFuelTypeQuery(routelistEntities);
                cvs_ft.Source = ftq.Execute(MergeOption.AppendOnly);
                id_main_fuel_typeTextBox.ItemsSource = cvs_ft; //ftq.Execute(MergeOption.AppendOnly);
            }
            grid1.DataContext = VehicleType;
            // Загрузить данные в vehicle_type. Можно изменить этот код как требуется.
            System.Windows.Data.CollectionViewSource vehicle_typeViewSource1 = ((System.Windows.Data.CollectionViewSource)(this.FindResource("vehicle_typeViewSource1")));
            System.Data.Objects.ObjectQuery<RL.vehicle_type> vehicle_typeQuery = this.Getvehicle_typeQuery(routelistEntities);
            vehicle_typeViewSource1.Source = vehicle_typeQuery.Execute(System.Data.Objects.MergeOption.AppendOnly);
            System.Windows.Data.CollectionViewSource vehicle_typeFuelVehicleTypeNormViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("vehicle_typeFuelVehicleTypeNormViewSource")));
            System.Data.Objects.ObjectQuery<RL.FuelVehicleTypeNorm> vehicleTypeFuelNormQuery = GetvehicleTypeFuelNorm(VehicleType);
            vehicle_typeFuelVehicleTypeNormViewSource.Source = vehicleTypeFuelNormQuery.Execute(MergeOption.AppendOnly);

            //CollectionViewSource cvsFuelType = (CollectionViewSource)this.Resources["FuelTypeSource"];
            //System.Data.Objects.ObjectQuery<fuel_type> fueltypequery = GetFuelTypeQuery(routelistEntities);
            //cvsFuelType.Source = fueltypequery.Execute(MergeOption.AppendOnly);
        }

        private void id_main_fuel_typeTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            //if (null == cur_item) return;
            //int id = cur_item.fuel_type.id;
        }

        private void buttonAdd_Click(object sender, RoutedEventArgs e)
        {
            CreateNew(VehicleType);
        }

        private void buttonDelete_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Data.CollectionViewSource vehicle_typeFuelVehicleTypeNormViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("vehicle_typeFuelVehicleTypeNormViewSource")));
            FuelVehicleTypeNorm item = vehicle_typeFuelVehicleTypeNormViewSource.View.CurrentItem as FuelVehicleTypeNorm;
            if (null == item) return;
            routelistEntities.DeleteObject(item);
            SaveData();
            System.Data.Objects.ObjectQuery<RL.FuelVehicleTypeNorm> vehicleTypeFuelNormQuery = GetvehicleTypeFuelNorm(VehicleType);
            vehicle_typeFuelVehicleTypeNormViewSource.Source = vehicleTypeFuelNormQuery.Execute(MergeOption.AppendOnly);
        }

        private void CreateNew(vehicle_type vehicle_type)
        {
            try
            {

                if (null == vehicle_type) return;
                fuel_type fitem = (from o in routelistEntities.fuel_type orderby o.name select o).FirstOrDefault();
                if (null == fitem) return;
                System.Windows.Data.CollectionViewSource vehicle_typeViewSource1 = ((System.Windows.Data.CollectionViewSource)(this.FindResource("vehicle_typeFuelVehicleTypeNormViewSource")));
                FuelVehicleTypeNorm item = ((IEditableCollectionView)vehicle_typeViewSource1.View).AddNew() as FuelVehicleTypeNorm;
                item.id_type_fuel = fitem.id;
                item.id_type_vehicle = VehicleType.id;
                //vehicle_type.FuelVehicleTypeNorm.Add(item);
                ((IEditableCollectionView)vehicle_typeViewSource1.View).CommitNew();
                //vehicle_type.FuelVehicleTypeNorm.Add(item);
            }
            catch (Exception)
            {
            }
        }

        private bool IsModified()
        {
            bool bResult = false;
            if (null == routelistEntities) return false;
            bResult = routelistEntities.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Added).Count() > 0 || routelistEntities.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Deleted).Count() > 0 || routelistEntities.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Modified).Count() > 0;
            return bResult;
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (IsModified())
            {
                var result = MessageBox.Show("Сохранить изменения?", "Предупреждение", MessageBoxButton.YesNoCancel, MessageBoxImage.Exclamation, MessageBoxResult.Yes);
                switch (result)
                {
                    case MessageBoxResult.Yes:
                        if (false == SaveData())
                        {
                            e.Cancel = true;
                        }
                        break;
                    case MessageBoxResult.Cancel:
                        e.Cancel = true;
                        break;
                }

            }
        }

        private bool SaveData()
        {
            bool bResult = true;
            try
            {
                routelistEntities.SaveChanges();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), Properties.Resources.DataSavingError, MessageBoxButton.OK, MessageBoxImage.Exclamation);
                bResult = false;
            }
            return bResult;
        }
    }
}
